<template>
  <!-- 顶部查询栏 -->
  <el-card style="height: 60px">
    <el-form ref="formRef" :model="myForm" :inline="true">
      <el-form-item label="工单编号" size="small" prop="workOrderId">
        <el-input v-model="myForm.workOrderId" placeholder="请输入工单编号" style="width: 150px;" clearable
          spellcheck="false" />
      </el-form-item>
      <el-form-item label="车主手机号" size="small" prop="phoneNumber">
        <el-input v-model="myForm.phoneNumber" placeholder="请输入车主手机号" style="width: 150px;" clearable
          spellcheck="false" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(formRef)" size="small">查询</el-button>
        <el-button @click="resetForm(formRef)" size="small">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 中间数据展示表格 -->
  <el-card style="height: 550px">
    <el-table :data="myResponse.tableData" stripe height="500" style="width: 100%">
      <!-- <el-table-column prop="id" label="id" min-width="50" align="center" /> -->
      <!-- min-width 宽度为170px 当行内有多余的空位按比例增加 -->
      <el-table-column prop="work_order_id" label="工单编号" min-width="170" align="center" />
      <el-table-column prop="order_type" label="工单类型" width="90" align="center" />
      <el-table-column prop="city_name" label="城市" width="90" align="center" />
      <el-table-column prop="area_name" label="区域" width="90" align="center" />
      <el-table-column prop="phone_number" label="车主手机号" min-width="110" align="center" />
      <el-table-column prop="listen_time" label="上牌时间" min-width="165" align="center" />
      <!-- 超过字段长度的内容显示为 ...  hover展示全部内容 -->
      <el-table-column prop="remark" label="备注信息" min-width="165" show-overflow-tooltip align="center" />
      <el-table-column label="操作" align="center" min-width="170">
        <!-- 表格列插槽 -->
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.row)" text style="padding:0">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" text style="padding:0">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 底部分页栏 -->
  <el-card style="height: 60px;">
    <el-pagination layout="total, prev, pager, next, jumper" :total=myResponse.count :small="true" background
      v-model:current-page="myForm.pageNum" @current-change="handleCurrentChange" />
  </el-card>
  <!-- 编辑弹框，摆放任意位置即可，会居中展示 -->
  <el-dialog v-model="dialogFormVisible" title="编辑工单" width=30% draggable>
    <el-form :model="dialogFrom" size="small" label-position="right" label-width="auto">
      <el-form-item label="工单编号">
        <!-- disabled 不可编辑 -->
        <el-input v-model="dialogFrom.workOrderId" disabled style="width: 160px" />
      </el-form-item>
      <el-form-item label="城市">
        <el-input v-model="dialogFrom.cityName" disabled style="width: 160px" />
      </el-form-item>
      <el-form-item label="区域">
        <el-input v-model="dialogFrom.areaName" disabled style="width: 160px" />
      </el-form-item>
      <el-form-item label="工单类型">
        <el-select v-model="dialogFrom.orderType" style="width: 160px;" disabled>
          <el-option label="优质工单" value=1 />
          <el-option label="普通工单" value=0 />
        </el-select>
      </el-form-item>
      <el-form-item label="车主手机号" prop="phoneNumber"
        :rules="[{ required: true, message: '请输入手机号', trigger: 'change' }]">
        <el-input v-model="dialogFrom.phoneNumber" style="width: 160px" />
      </el-form-item>
      <el-form-item label="备注信息">
        <el-input style="width: 200px" :rows="3" type="textarea" placeholder="工单备注信息" clearable spellcheck="false"
          v-model="dialogFrom.remark" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogFromSubmit" :disabled="dialogSubmitDisable">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import request from '@/utils/request'
// 引入消息提示、消息弹出框、消息通知
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
// 引入删除消息弹框中使用的垃圾箱图标
import { markRaw } from 'vue'
import { Delete } from '@element-plus/icons-vue'


// ref 关联表单
const formRef = ref()

// 查询提交表单数据
const myForm = reactive({
  pageNum: '',
  pageSize: 10,
  phoneNumber: '',
  workOrderId: ''
})

// 查询返回数据
const myResponse = reactive({
  count: 0,
  tableData: []
})
// 工单类型映射字典
const orderTypeObj = reactive({ 0: "普通工单", 1: "优质工单" })

// 对话展示标志
const dialogFormVisible = ref(false)

// 对话框内表单数据
const dialogFrom = reactive({
  workOrderId: '',
  cityName: '',
  areaName: '',
  orderType: '',
  phoneNumber: '',
  remark: '',
  originPhoneNumber: '',
  originRemark: ''
})
// 对话框内提交不可用标识
const dialogSubmitDisable = ref(true)

// 进入页面默认触发查询
onMounted(async () => {
  // async和await组合使用，发送请求后返回promise对象，res.data为响应参数
  await request.get("/partner/order").then((res) => {
    myResponse.count = res.data.count
    let data = res.data.data
    data.forEach(ele => {
      // 工单类型，数字转换文字
      ele['order_type'] = orderTypeObj[ele['order_type']]
      myResponse.tableData.push(ele)
    })
  }).catch(() => {
    ElNotification({
      title: '失败',
      message: '服务内部错误！',
      type: 'error',
    })
  })
})

// 点击分页触发查询
const handleCurrentChange = async () => {
  myResponse.tableData = []
  let data = {
    page_num: myForm.pageNum,
    page_size: myForm.pageSize,
    work_order_id: myForm.workOrderId,
    phone_number: myForm.phoneNumber
  }
  await request.get("/partner/order", data).then((res) => {
    myResponse.count = res.data.count
    data = res.data.data
    data.forEach(ele => {
      ele['order_type'] = orderTypeObj[ele['order_type']]
      myResponse.tableData.push(ele)
    })
  }).catch(() => {
    ElNotification({
      title: '失败',
      message: '服务内部错误！',
      type: 'error',
    })
  })
}

// 查询提交
const onSubmit = (formEl) => {
  if (!formEl) return
  // 必填项校验
  formEl.validate(async (valid) => {
    if (valid) {
      // 清空表格，分页定到首页
      myResponse.tableData = []
      myForm.pageNum = 1
      let data = {
        page_num: myForm.pageNum,
        page_size: myForm.pageSize,
        work_order_id: myForm.workOrderId,
        phone_number: myForm.phoneNumber
      }
      await request.get("/partner/order", data).then((res) => {
        myResponse.count = res.data.count
        let response = res.data.data
        response.forEach(ele => {
          ele['order_type'] = orderTypeObj[ele['order_type']]
          myResponse.tableData.push(ele)
        })
      }).catch(() => {
        ElNotification({
          title: '失败',
          message: '服务内部错误！',
          type: 'error',
        })
      })
    }
  })
}

// 查询重置
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}


// 删除工单
const handleDelete = (row) => {
  // 消息弹框
  ElMessageBox.confirm(
    '确认删除此工单  【' + row.work_order_id + '】',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      icon: markRaw(Delete),
      draggable: true
    }
  )
    // 确认提交操作
    .then(async () => {
      // 调用删除接口
      await request.delete('/partner/order', { id: row.id })
        // 接口响应成功，响应码200
        .then(res => {
          // 进一步判断业务，code 0 成功 code -1 失败
          if (res.data.code == 0) {
            ElNotification({
              title: '成功',
              message: '工单已删除',
              type: 'success',
            })
            // 重新发起查询，调用分页方法最合适，不会定位到首页
            handleCurrentChange()
          } else {
            ElNotification({
              title: '警告',
              // 工单不存在
              message: res.data.msg,
              type: 'warning'
            })
          }
          // 接口响应失败，响应码大于300，如服务挂了 nginx 502 // 接口超时 // then分支内部报错
        }).catch(() => {
          ElNotification({
            title: '失败',
            message: '服务内部错误！',
            type: 'error'
          })
        })
    })
    // 取消操作
    .catch(() => {
      // 取消操作不做任何提示
    })
}

// 编辑工单弹框
const handleEdit = (row) => {
  dialogFormVisible.value = true
  dialogFrom.id = row.id
  dialogFrom.workOrderId = row.work_order_id
  dialogFrom.orderType = row.order_type
  dialogFrom.cityName = row.city_name
  dialogFrom.areaName = row.area_name
  dialogFrom.phoneNumber = row.phone_number
  dialogFrom.remark = row.remark
  dialogFrom.originPhoneNumber = row.phone_number,
    dialogFrom.originRemark = row.remark
}

// 编辑工单提交
const dialogFromSubmit = async () => {
  // 发送请求编辑请求
  let data = {
    id: dialogFrom.id,
    phone_number: dialogFrom.phoneNumber,
    remark: dialogFrom.remark
  }
  await request.put('/partner/order', data)
    // 接口响应成功，响应码200
    .then((res) => {
      // 进一步判断业务
      if (res.data.code == 0) {
        ElNotification({
          title: '成功',
          message: '工单编辑成功',
          type: 'success'
        })
        // 重新发起查询，调用分页方法最合适，不会定位到首页
        handleCurrentChange()
        // 将提交按钮至为不可用
        dialogSubmitDisable.value = true
        // 关闭弹框
        dialogFormVisible.value = false
      } else {
        ElNotification({
          title: '警告',
          // 工单不存在
          message: res.data.msg,
          type: 'warning'
        })
      }
      // 接口响应失败，响应码大于300，如服务挂了 nginx 502 // 接口超时 // then分支内部报错
    }).catch(() => {
      ElNotification({
        title: '失败',
        message: '服务内部错误！',
        type: 'error',
      })
    })
}

// 监听编辑对话框，手机号和备注是否发生变化，如果发生变化则可提交，否则不可提交
watch(() => dialogFrom.phoneNumber, (newValue) => {
  if (newValue == dialogFrom.originPhoneNumber && dialogFrom.remark == dialogFrom.originRemark) {
    dialogSubmitDisable.value = true
  } else {
    dialogSubmitDisable.value = false
  }
})
watch(() => dialogFrom.remark, (newValue) => {
  if (newValue == dialogFrom.originRemark && dialogFrom.phoneNumber == dialogFrom.originPhoneNumber) {
    dialogSubmitDisable.value = true
  } else {
    dialogSubmitDisable.value = false
  }
})
</script>
